#include "mtf.h"
#include <string.h>

int verbose = 0;

int main(int argc, char** argv){
  unsigned char *string, *encrypted, *decrypted;
  int length;
  string = "Hello, my name is Bob. Nice to meet you!";
  length = strlen(string);
  encrypted = malloc(length*sizeof(unsigned char));
  memset(encrypted, 0, length*sizeof(unsigned char));
  decrypted = malloc(length*sizeof(unsigned char));
  memset(decrypted, 0, length*sizeof(unsigned char));
  verbose = 1;

  mtfencode(encrypted, string, length);
  mtfdecode(decrypted, encrypted, length);

  printf("%s\n%s\n%s\n", string, encrypted, decrypted); 
}

int mtfencode(unsigned char* dst, unsigned char* src, int length){
  int i, j;
  unsigned char table[256];
  for(i = 0; i < 256; i++)
    table[i] = i;
  for(i = 0; i < length; i++){
    for(j = 0; j < 256; j++)
      if(src[i] == table[j])
        break;
    if(j >= 256)
      return -1;
    dst[i] = j;
    if(verbose) printf("%d\n", j);
    for( ; j > 0; j--)
      table[j] = table[j-1];
    table[0] = src[i];
  }
  dst[i] = '\0';
}

int mtfdecode(unsigned char* dst, unsigned char* src, int length){
  int i, j;
  char table[256];
  for(i = 0; i < 256; i++)
    table[i] = i;
  for(i = 0; i < length; i++){
    dst[i] = table[src[i]];
    for(j = src[i]; j > 0; j--)
      table[j] = table[j-1];
    table[0] = dst[i];
  }
  dst[i] = '\0';
}
